package com.zjm.json.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;

/**
 * @author ZJM
 * @date 2024/4/18 21:51
 */
public class JacksonUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将JSON字符串转换为指定类型的对象
     * @param json
     * @param clazz
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> T jsonToObject(String json, Class<T> clazz) throws IOException {
        return objectMapper.readValue(json, clazz);
    }

    /**
     * 将Java对象转换为JSON字符串
     * @param object
     * @return
     * @throws IOException
     */
    public static String objectToJson(Object object) throws IOException {
        return objectMapper.writeValueAsString(object);
    }

    /**
     * 将JSON字符串转换为Map<K, V>
     * @param json
     * @param <K>
     * @param <V>
     * @return
     * @throws IOException
     */
    public static <K, V> Map<K, V> jsonToMap(String json) throws IOException {
        return objectMapper.readValue(json, new TypeReference<Map<K, V>>() {});
    }

    /**
     * 将Map<K, V>转换为JSON字符串
     * @param map
     * @param <K>
     * @param <V>
     * @return
     * @throws IOException
     */
    public static <K, V> String mapToJson(Map<K, V> map) throws IOException {
        return objectMapper.writeValueAsString(map);
    }
}
